#!/usr/bin/env python3
"""
Flask-APScheduler初始化脚本
"""

import os
import sys
import logging

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

from apps.extensions import db
from apps.modules.admin.models.sys.sys_task import Task
from apps.extensions.scheduler import init_scheduler, load_existing_tasks, add_job_from_task
from .decorator.ext_decorator import ext_decorator
@ext_decorator
def init_task_scheduler(app):
    """初始化任务调度器"""
    try:
        # 初始化调度器
        scheduler = init_scheduler(app)
        logger.info("✅ 调度器初始化成功")
        
        # 在应用上下文中加载任务
        with app.app_context():
            load_existing_tasks()
        
        return scheduler
        
    except Exception as e:
        logger.error(f"❌ 调度器初始化失败: {e}")
        return None

def load_tasks_from_database():
    """从数据库加载任务到调度器"""
    try:
        tasks = Task.query.filter_by(enabled=True).all()
        logger.info(f"📊 从数据库加载 {len(tasks)} 个任务")
        
        loaded_count = 0
        for task in tasks:
            try:
                job = add_job_from_task(task)
                if job:
                    logger.info(f"  ✅ 加载任务: {task.name} ({task.id})")
                    loaded_count += 1
                else:
                    logger.warning(f"  ⚠️  加载任务失败: {task.name} ({task.id})")
            except Exception as e:
                logger.error(f"  ❌ 加载任务失败: {task.name} - {e}")
        
        logger.info(f"✅ 成功加载 {loaded_count}/{len(tasks)} 个任务")
        return True
        
    except Exception as e:
        logger.error(f"❌ 加载任务失败: {e}")
        return False

def create_sample_tasks():
    """创建示例任务"""
    try:
        # 检查是否已有任务
        if Task.query.count() > 0:
            logger.info("⚠️  数据库中已有任务数据")
            return True
        
        # 创建示例任务
        sample_tasks = [
            Task(
                id='test_task_1',
                name='测试任务1',
                func='test_task',
                trigger='interval',
                trigger_args='{"hours": 1}',
                enabled=True
            ),
            Task(
                id='clean_logs_1',
                name='清理日志',
                func='clean_logs',
                trigger='cron',
                trigger_args='{"hour": 2, "minute": 0}',
                enabled=True
            ),
            Task(
                id='backup_db_1',
                name='数据库备份',
                func='backup_database',
                trigger='cron',
                trigger_args='{"hour": 3, "minute": 0}',
                enabled=False
            )
        ]
        
        for task in sample_tasks:
            db.session.add(task)
        
        db.session.commit()
        logger.info(f"✅ 成功创建 {len(sample_tasks)} 个示例任务")
        return True
        
    except Exception as e:
        logger.error(f"❌ 创建示例任务失败: {e}")
        db.session.rollback()
        return False

def check_scheduler_status():
    """检查调度器状态"""
    try:
        from apps.extensions.scheduler import scheduler
        
        jobs = scheduler.get_jobs()
        logger.info(f"📊 调度器状态: {len(jobs)} 个活跃作业")
        
        if jobs:
            logger.info("活跃作业列表:")
            for job in jobs:
                logger.info(f"  - {job.id}: {job.name} (下次运行: {job.next_run_time})")
        else:
            logger.info("没有活跃的作业")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ 检查调度器状态失败: {e}")
        return False

def main():
    """主函数"""
    logger.info("🚀 开始初始化任务调度器...")
    print("=" * 50)
    
    # 这里需要Flask应用上下文
    # 在实际使用时，应该在Flask应用中调用
    logger.info("💡 使用说明:")
    logger.info("1. 在Flask应用中导入并调用 init_task_scheduler(app)")
    logger.info("2. 确保已安装 Flask-APScheduler: pip install Flask-APScheduler")
    logger.info("3. 运行数据库迁移创建任务表")
    logger.info("4. 访问任务管理页面: /admin/sys/task/")
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1) 